package com.dingreading.cloud.common.util;

import org.apache.commons.lang3.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 验证日期时间字符串是否合法
 */
public class DateTimeValidator {

    private static final String DATE_PATTERN = "yyyy-MM-dd";
    private static final String TIME_PATTERN = "HH:mm:ss";

    public static boolean isValidDate(String date) {
        return isValidFormat(DATE_PATTERN, date);
    }

    public static boolean isValidTime(String time) {
        return isValidFormat(TIME_PATTERN, time);
    }

    private static boolean isValidFormat(String pattern, String value) {
        if (StringUtils.isBlank(value))
            return false;

        DateFormat formatter = new SimpleDateFormat(pattern);
        try {
            Date date = formatter.parse(value);
            return value.equals(formatter.format(date));
        } catch (Exception e) {
            return false;
        }
    }

}
